var setSocialAccount = function(fullname,email) {
    $('#app_input_fullname').val(fullname);
    $('#app_input_email').val(email);
};

$.ajaxSetup({ cache: true });

// Facebook
$('#app_social_facebook').click(function () {
    $.getScript('//connect.facebook.net/en_US/all.js', function () {
        FB.init({
            appId: '1446046578961446',
            status: true,
            cookie: true,
            xfbml: true
        });
        var permision = ['email'];
        var field = ['name'];

        FB.login(function (auth) {
            if (typeof auth.authResponse.accessToken!=undefined) {
                $.ajax({url: "https://graph.facebook.com/me?access_token=" + auth.authResponse.accessToken, success: function (result) {
                    setSocialAccount(result.name,result.email);
                }});
            }
        }, {scope: permision});
    });
});

// Google+
$('#app_social_google').click(function () {
    $.getScript("//apis.google.com/js/client:plusone.js");
    $('#___signin_0 button').click();
});

// Yahoo
$('#app_social_yahoo').click(function () {
    var loginYahoo = function(url) {
        var yhwindow = window.open(url,'');

    };
    $.ajax({url: 'syn/yahoo', success: function (result) {
        if (result.login==0) {
            loginYahoo(result.url);
        } else {
            setSocialAccount(result.name,result.email);
        }
    }});
});

//----------------------------------

var profile, email;

function loginFinishedCallback(authResult) {
    if (authResult) {
        if (authResult['error'] == undefined) {
            gapi.client.load('plus', 'v1', loadProfile);
        }
    }
}

function loadProfile() {
    var request = gapi.client.plus.people.get({'userId': 'me'});
    request.execute(loadProfileCallback);
}

function loadProfileCallback(obj) {
    var profile = obj;
    var email = obj['emails'].filter(function (v) {
        return v.type === 'account';
    })[0].value;
    var name = profile['displayName'];
    setSocialAccount(name,email);
}
